package com.ruoyi.web.controller.statistic.admin;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.ConfigConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.vo.ImportProgressVo;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MathUtils;
import com.ruoyi.common.utils.OrikaUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.statistic.domain.StatisticStudentBaseInfo;
import com.ruoyi.statistic.domain.vo.*;
import com.ruoyi.statistic.service.IStatisticStudentBaseInfoService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.io.File;

@RestController("AdminStatisticStudentBaseInfoController")
@RequestMapping("/admin/employment/statistic/student/baseInfo")
public class StatisticStudentBaseInfoController extends BaseController {

    @Resource
    private IStatisticStudentBaseInfoService statisticStudentBaseInfoService;

    @Resource
    private ISysConfigService configService;

    @Resource
    private RedisCache redisCache;

//    @Resource
//    private ISysUserStudentService userStudentService;

    /**
     * 查询统计学生列表
     */
    @GetMapping("/list")
    public TableDataInfo list(StatisticStudentListSearchVo vo) {
        startPage();
        List<StatisticStudentBaseInfo> list = statisticStudentBaseInfoService.selectStatisticStudentBaseInfoListBySearchVo(vo);
        return getDataTable(list);
    }

    /**
     * 导出学生管理列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, StatisticStudentListSearchVo vo) {
        List<StatisticStudentBaseInfo> list = statisticStudentBaseInfoService.selectStatisticStudentBaseInfoListBySearchVo(vo);
        ExcelUtil<StatisticStudentBaseInfo> util = new ExcelUtil<>(StatisticStudentBaseInfo.class);
        util.exportExcel(response, list, "学生管理数据");
    }

    /**
     * 获取学生管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(statisticStudentBaseInfoService.selectStatisticStudentBaseInfoById(id));
    }

    /**
     * 新增学生
     */
    @Log(title = "学生管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StatisticStudentBaseInfo statisticStudentBaseInfo) {
        return toAjax(statisticStudentBaseInfoService.insertStatisticStudentBaseInfo(statisticStudentBaseInfo));
    }

    /**
     * 修改学生管理
     */
    @Log(title = "学生管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StatisticStudentBaseInfo statisticStudentBaseInfo) {
        return toAjax(statisticStudentBaseInfoService.updateStatisticStudentBaseInfo(statisticStudentBaseInfo));
    }

    /**
     * 删除学生管理
     */
    @Log(title = "学生管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(statisticStudentBaseInfoService.deleteStatisticStudentBaseInfoByIds(ids));
    }


    /**
     * 上传学生基础信息文件
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadData")
    public AjaxResult uploadDataFile(MultipartFile file) throws IOException {
        String fileExt = FileUploadUtils.getExtension(file);//文件后缀名
        String newName = UUID.fastUUID().toString().replace("-", "");//随机生成uuid文件名
        String configPath = configService.selectConfigByKey(ConfigConstants.SYS_UPLOAD_DATA_FILE_PATH);
        String savePath = configPath + newName + "." + fileExt;
        File newFile = new File(savePath);
        file.transferTo(newFile);
        return success(newName + "." + fileExt);
    }


    /**
     * 导入excel的档案寄送记录
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/importData")
    @Log(title = "导入档案寄送记录管理", businessType = BusinessType.IMPORT)
    public AjaxResult importData(@RequestBody StatisticUploadFileVo fileReq) throws Exception {
        //获取上传路径
        String configPath = configService.selectConfigByKey(ConfigConstants.SYS_UPLOAD_DATA_FILE_PATH);
        File file = new File(configPath + fileReq.getFileName());
        ExcelUtil<StatisticStudentInfoTemplateVo> util = new ExcelUtil<>(StatisticStudentInfoTemplateVo.class);
        InputStream is = new FileInputStream(file);
        //将当前excel保存到excel
        List<StatisticStudentInfoTemplateVo> recordList = util.importExcel(is);//导入流转list
        List<StudentInfoTemplateResultVo> resultList = new ArrayList<>();
        ImportProgressVo progressVo = new ImportProgressVo();
        if (recordList != null && recordList.size() > 0) {
            //获取当前导入用户
            LoginUser user = getLoginUser();
            progressVo.setCountNum(recordList.size());//获取数据总数
            for (StatisticStudentInfoTemplateVo vo : recordList) {
                StudentInfoTemplateResultVo resultVo = OrikaUtils.convert(vo, StudentInfoTemplateResultVo.class);
                try {
                    //判断当前学生是否已经存在
                    StatisticStudentBaseInfo info = statisticStudentBaseInfoService.selectStatisticStudentBaseInfoByCode(vo.getCode());
                    //存在
                    if (info != null) {
                        Long id = info.getId();//暂存当前的id
                        info = OrikaUtils.convert(vo, StatisticStudentBaseInfo.class);
                        info.setId(id);
                        info.setUpdateBy(user.getUsername());
                        statisticStudentBaseInfoService.updateStatisticStudentBaseInfo(info);
                        resultVo.setOpStatus("更新成功");
                        resultList.add(resultVo);
                    }
                    //不存在
                    else {
                        info = OrikaUtils.convert(vo, StatisticStudentBaseInfo.class);
                        info.setCreateBy(user.getUsername());
                        statisticStudentBaseInfoService.insertStatisticStudentBaseInfo(info);
                        resultVo.setOpStatus("添加成功");
                        resultList.add(resultVo);
                    }
                    progressVo.addSuccessNum();
                } catch (Exception ex) {
                    //出错
                    resultVo.setOpStatus("导入失败");
                    resultVo.setMsg(ex.getMessage());
                    resultList.add(resultVo);
                    progressVo.addFailureNum();
                }
                progressVo.addOpNum();
                String percent = MathUtils.calcPercent_CEILING(progressVo.getOpNum(), progressVo.getCountNum());//设置百分比，只展示百分比的整数部分
                redisCache.setCacheObject(fileReq.getFileName(), percent);
            }
        }
        String fileExt = file.getName().substring(file.getName().lastIndexOf("."), file.getName().length());
        String newName = UUID.fastUUID().toString().replace("-", "");//随机生成uuid文件名
        String configResultPath = configService.selectConfigByKey(ConfigConstants.SYS_UPLOAD_RESULT_FILE_PATH);
        String resultFileName = configResultPath + newName + fileExt;
        EasyExcel.write(resultFileName, StudentInfoTemplateResultVo.class).sheet("sheet1").registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).doWrite(resultList);
        progressVo.setResultFileName(newName + fileExt);
        redisCache.setCacheObject(fileReq.getFileName(), "100");
        //TODO 导入完成后，需要删除数据 或者 定时删除数据
        return success(progressVo);
    }


    /**
     * 获取当前文件的导出进度
     *
     * @return
     */
//    @PreAuthorize("@ss.hasPermi('system:archive:importDataProgress')")
    @GetMapping("/importDataProgress/{fileName}")
//    @Log(title = "获取学生基础数据文件导入记录", businessType = BusinessType.OTHER)
    public AjaxResult importDataProgress(@PathVariable("fileName") String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return success("0");
        }
        String percent = redisCache.getCacheObject(fileName);
        if (StringUtils.isEmpty(percent)) {
            return success("0");
        }
        return success(percent);
    }


    /**
     * 导出上传结果
     *
     * @param response
     * @throws Exception
     * @RequestBody UploadFileVo fileReq,
     */
    @PostMapping("/exportUploadResult")
    public void exportUploadResult(@RequestParam(value = "fileName") String fileName, HttpServletResponse response) throws Exception {
        String path = configService.selectConfigByKey(ConfigConstants.SYS_UPLOAD_RESULT_FILE_PATH);
        String filePath = path + fileName;
        File file = new File(filePath);
        if (file.exists()) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        }
    }

    /**
     * 导出基础数据
     */
    @Log(title = "导出基础数据", businessType = BusinessType.EXPORT)
    @PostMapping("/exportlist")
    public void exportlist(HttpServletResponse response, StatisticStudentListSearchVo statisticStudentListSearchVo) {
        List<StatisticStudentBaseInfo> list = statisticStudentBaseInfoService.selectStatisticStudentBaseInfoListBySearchVo(statisticStudentListSearchVo);
        ExcelUtil<StatisticStudentBaseInfo> util = new ExcelUtil<>(StatisticStudentBaseInfo.class);
        util.exportExcel(response, list, "学生数据");
    }


    /**
     * 下载学生信息导入模板文件
     *
     * @param response
     */
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws Exception {
        String fileName = "student_employment_base_template.xlsx";
        String path = configService.selectConfigByKey(ConfigConstants.SYS_TEMPLATE_DOWNLOAD_PATH);
        String filePath = path + fileName;
        File file = new File(filePath);
        if (file.exists()) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        }
    }


    /**
     * 设置带兵
     *
     * @param vo
     * @return
     */
    @PutMapping(value = "/set/lead")
    public AjaxResult lead(@RequestBody StatisticUpdateLeadVo vo) {
        statisticStudentBaseInfoService.batchUpdateLead(vo);
        return success("操作成功！");
    }


    /**
     * 设置学生系别专业
     *
     * @param vo
     * @return
     */
    @PutMapping(value = "/set/department/major")
    public AjaxResult degree(@RequestBody StatisticUpdateDegreeVo vo) {
        if (StringUtils.isEmpty(vo.getDepartment()) && StringUtils.isEmpty(vo.getMajor())) {
            return error("系别和专业不能同时为空！");
        }
        statisticStudentBaseInfoService.batchUpdateDegree(vo);
        return success("操作成功！");
    }
}
